﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Snowdreamist.Collection.Tree
{
    public class BinaryTreeNodeCollection<T> : ITreeNodeCollection<T> where T : BinaryTreeNode<T>
    {
        public int IndexOf(T item)
        {
            if (this._children[0] != null && this._children[0].Equals(item))
                return 0;
            else if (this._children[1] != null && this._children[1].Equals(item))
                return 1;
            else
                return -1;
        }

        public void Insert(int index, T item)
        {
            throw new NotSupportedException();
        }

        public void RemoveAt(int index)
        {
            if (index < 0 || index > 1)
                throw new IndexOutOfRangeException();
            this._children[index] = null;
        }

        public T this[int index]
        {
            get
            {
                if (index < 0 || index > 1)
                    throw new IndexOutOfRangeException();
                return this._children[index];
            }
            set
            {
                if (index < 0 || index > 1)
                    throw new IndexOutOfRangeException();
                this._children[index] = value;
            }
        }

        public void Add(T item)
        {
            throw new NotSupportedException();
        }

        public void Clear()
        {
            this._children[0] = null;
            this._children[1] = null;
        }

        public bool Contains(T item)
        {
            if (item != null)
                return (this._children[0] != null && this._children[0].Equals(item)) || (this._children[1] != null && this._children[1].Equals(item));
            else
                return this._children[0] == null || this._children[1] == null;
        }

        public void CopyTo(T[] array, int arrayIndex)
        {
            this._children.CopyTo(array, arrayIndex);
        }

        public int Count
        {
            get
            {
                return 2;
            }
        }

        public bool IsReadOnly
        {
            get
            {
                return false;
            }
        }

        public bool Remove(T item)
        {
            int index = this.IndexOf(item);
            if (index == -1)
                return false;
            this._children[index] = null;
            return true;
        }

        public IEnumerator<T> GetEnumerator()
        {
            foreach (var child in this._children)
                yield return child;
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        private readonly T[] _children = new T[2];
    }
}